package org.zebra.web.filter;

import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.zebra.common.util.UriWhiteUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Repeatable 过滤器
 *
 * @author zhanghongbin
 */
@AllArgsConstructor
public class RepeatableFilter extends OncePerRequestFilter {

    private PathMatcher pathMatcher;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        filterChain.doFilter(new RepeatedlyRequestWrapper(request, response), response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String uri = request.getServletPath();
        boolean flag = UriWhiteUtil.getDefaultUriWhite().stream()
                .anyMatch(excludeUrl -> pathMatcher.matchStart(excludeUrl, uri));
        if (flag) return true;
        // 只处理 json 请求内容
        return !StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE);
    }
}
